#Boa:Dialog:comisiones

import wx
import wx.grid
import datetime

import consultasBD

import ruleManager
import sellManager
import utiles

from decimal import Decimal

def create(parent):
    return comisiones(parent)

[wxID_COMISIONES, wxID_COMISIONESBUTTON1, wxID_COMISIONESGRID1, 
 wxID_COMISIONESMONTHCOMBO, wxID_COMISIONESSTATICTEXT1, 
 wxID_COMISIONESSTATICTEXT2, wxID_COMISIONESYEARCOMBO, 
] = [wx.NewId() for _init_ctrls in range(7)]

class comisiones(wx.Dialog):
    def _init_ctrls(self, prnt):
        # generated method, don't edit
        wx.Dialog.__init__(self, id=wxID_COMISIONES, name='comisiones',
              parent=prnt, pos=wx.Point(66, 80), size=wx.Size(595, 378),
              style=wx.DEFAULT_DIALOG_STYLE, title='Comisiones')
        self.SetClientSize(wx.Size(587, 351))

        self.grid1 = wx.grid.Grid(id=wxID_COMISIONESGRID1, name='grid1',
              parent=self, pos=wx.Point(16, 40), size=wx.Size(560, 296),
              style=0)

        self.staticText1 = wx.StaticText(id=wxID_COMISIONESSTATICTEXT1,
              label='A\xf1o:', name='staticText1', parent=self, pos=wx.Point(16,
              8), size=wx.Size(24, 13), style=0)

        self.staticText2 = wx.StaticText(id=wxID_COMISIONESSTATICTEXT2,
              label='Mes:', name='staticText2', parent=self, pos=wx.Point(104,
              8), size=wx.Size(24, 13), style=0)

        self.yearCombo = wx.ComboBox(choices=[], id=wxID_COMISIONESYEARCOMBO,
              name='yearCombo', parent=self, pos=wx.Point(48, 8),
              size=wx.Size(48, 21), style=wx.CB_READONLY | wx.CB_SIMPLE,
              value='comboBox1')

        self.monthCombo = wx.ComboBox(choices=[], id=wxID_COMISIONESMONTHCOMBO,
              name='monthCombo', parent=self, pos=wx.Point(136, 8),
              size=wx.Size(112, 21), style=wx.CB_READONLY, value='comboBox2')

        self.button1 = wx.Button(id=wxID_COMISIONESBUTTON1, label='Cargar',
              name='button1', parent=self, pos=wx.Point(502, 8),
              size=wx.Size(75, 23), style=0)
        self.button1.Bind(wx.EVT_BUTTON, self.OnLoadButton,
              id=wxID_COMISIONESBUTTON1)

    def __init__(self, parent):
        self._init_ctrls(parent)
        print "COMISIONES 2"

        self.year = datetime.date.today().year
        self.month = datetime.date.today().month

        self.populateYearAndMonths()
        self.crearGrilla()
        
    def populateYearAndMonths(self):
        anioinicial = 2008
        anioactual = int(utiles.obtenerFecha("Y-m-d")[:4])+1
        for year in range(anioinicial, anioactual):
            self.yearCombo.Append(str(year))
        self.yearCombo.SetSelection(len(self.yearCombo.GetItems())-1)
        self.monthCombo.Append("Enero")
        self.monthCombo.Append("Febrero")
        self.monthCombo.Append("Marzo")
        self.monthCombo.Append("Abril")
        self.monthCombo.Append("Mayo")
        self.monthCombo.Append("Junio")
        self.monthCombo.Append("Julio")
        self.monthCombo.Append("Agosto")
        self.monthCombo.Append("Septiembre")
        self.monthCombo.Append("Octubre")
        self.monthCombo.Append("Noviembre")
        self.monthCombo.Append("Diciembre")
        self.monthCombo.SetSelection(self.month-1)
        
    def ajustarColumnas(self):
        for col in xrange(self.grid1.GetNumberCols()):
            self.grid1.AutoSizeColumn(col,True)
    
    def crearGrilla(self):
        #vendedora,en pesos,tarjetas,ctacte,monto,comision,puntos,nc
        #0         1        2        3      4     5        6      7
        columnas =['Vendedora','En Pesos','Tarjetas\n/otros','Cta.Cte.','Monto Vendido','Comision','Puntos','N.C.']
        columnas =['Vendedora','Monto Vendido','En Pesos','Tarjetas\n/otros','Cta.Cte.','Comision','Puntos']
        self.grid1.CreateGrid(1,len(columnas))
        for i, col in enumerate(columnas):
            self.grid1.SetColLabelValue(i, col)
        self.grid1.AutoSizeRow(0,True)
        self.ajustarColumnas()
        
    def limpiaGrilla(self):
        self.grid1.ClearGrid()
        for x in xrange(self.grid1.GetNumberRows()):
            self.grid1.DeleteRows()
        self.grid1.AppendRows()

    def OnLoadButton(self, event):
##        anio = self.yearCombo.GetLabel()
##        mes = self.monthCombo.GetLabel()
##        fechaInicio = "%s-%s-01 00:00:00" % (anio,mes)
##        fechaFinal= "%s-%s-31 23:59:59" % (anio,mes)
##        r1 = "SELECT v.idventa,v.totalfactura,v.usuario,vd.nombre FROM ventas v,vendedoras vd \n"
##        r2 = "WHERE v.usuario=vd.idvendedora AND v.totalfactura >0 \n"
##        r3 = "      AND fecha BETWEEN '"+fechaInicio+"' AND '"+fechaFinal+"' "
##        sql = r1+r2+r3
##        resultados = consultasBD.ordenCrudaDict(sql)
##
##        r1 = "SELECT SUM(v.totalfactura) AS total,v.usuario,vd.nombre \n"
##        r2 = "FROM ventas v,vendedoras vd \n"
##        r3 = "WHERE v.usuario=vd.idvendedora AND v.totalfactura>0 \n"
##        r4 = "      AND fecha BETWEEN '2012-03-01 00:00:00' AND '2012-03-31 23:59:59' \n"
##        r5 = "GROUP BY v.usuario ORDER BY total DESC "
##        sql = r1+r2+r3+r4+r5
##        resultados = consultasBD.ordenCrudaDict(sql)

##        year = self.yearCombo.GetValue()
##        month = self.monthCombo.GetValue()
        year = self.yearCombo.GetLabel()
        month = self.monthCombo.GetSelection()+1
        print "Mes procesado:",self.monthCombo.GetItems()[month]
        self.limpiaGrilla()
        
        fechaInicio= '%s-%s-01' % (year, month)
        fechaFinal= '%s-%s-31' % (year, month)
##        r01 = "SELECT b.idvendedora, b.nombre AS 'Nombre', SUM( totalfactura ) AS 'Total', \n"
##        r02 = "      (SELECT sum( monto )FROM ventastienepagos c \n"
##        r03 = "       WHERE idformapagos = 'P' AND c.vendedora = b.idvendedora \n"
##        r04 = "             AND c.vendedora=a.usuario \n"
##        r05 = "             AND (fecha>='%s' AND fecha<='%s')) AS Pesos, \n" % (fechaInicio,fechaFinal)
##        r06 = "      (SELECT sum( monto) FROM ventastienepagos c \n"
##        r07 = "       WHERE idformapagos <>'P' AND c.vendedora = b.idvendedora \n"
##        r08 = "             AND c.vendedora=a.usuario \n"
##        r09 = "             AND (fecha>='%s' AND fecha<='%s')) AS Tarjetas \n" % (fechaInicio,fechaFinal)
##        r10 = "FROM ventas a, vendedoras b \n"
##        r11 = "WHERE a.usuario = b.idvendedora \n"
##        r12 = "      AND (a.fecha>='%s' AND a.fecha<='%s') \n" % (fechaInicio,fechaFinal)
##        r13 = "      AND idformaticket!=999 \n"
##        r14 = "GROUP BY Nombre ORDER BY Total DESC \n"
        r01 = "SELECT b.idvendedora, b.nombre AS 'Nombre', SUM( totalfactura ) AS 'Total', \n"
        r02 = "      (SELECT sum( monto )FROM ventastienepagos c \n"
        r03 = "       WHERE idformapagos = 'P' AND c.vendedora = b.idvendedora \n"
        r04 = "             AND c.vendedora=a.usuario \n"
        r05 = "             AND (fecha>='%s' AND fecha<='%s')) AS Pesos, \n" % (fechaInicio,fechaFinal)
        r06 = "      (SELECT sum( monto) FROM ventastienepagos c \n"
        r07 = "       WHERE idformapagos <>'P' AND c.vendedora = b.idvendedora \n"
        r08 = "             AND c.vendedora=a.usuario \n"
        r09 = "             AND (fecha>='%s' AND fecha<='%s')) AS Tarjetas \n" % (fechaInicio,fechaFinal)
        r10 = "FROM ventas a, vendedoras b \n"
        r11 = "WHERE a.usuario = b.idvendedora \n AND a.totalfactura>0 \n"
        r12 = "      AND (a.fecha>='%s' AND a.fecha<='%s') \n" % (fechaInicio,fechaFinal)
        r13 = "      AND idformaticket!=999 \n"
        r14 = "GROUP BY Nombre ORDER BY Total DESC \n"
        SQL = r01+r02+r03+r04+r05+r06+r07+r08+r09+r10+r11+r12+r13+r14
        resultados = consultasBD.ordenCrudaDict(SQL)
        i =0 
        #rules = ruleManager.get_rules(2011, month)
        marca = False
        for r in resultados:
            #self.grid1.AppendRows()
            total = Decimal("0.0")
            pesos = Decimal("0.0")
            tarjetas = Decimal("0.0")
            ctacte = Decimal("0.0")
            if r["Nombre"] != None:
                self.grid1.SetCellValue(i, 0, str(r["Nombre"]))
            
            if r["Total"] != None:
                total = Decimal(str(r["Total"])).quantize(Decimal("0.10"))
                self.grid1.SetCellValue(i, 1, str(round(r["Total"],2)))
                
            if r["Pesos"] != None :
                pesos = Decimal(str(r["Pesos"])).quantize(Decimal("0.10"))
                self.grid1.SetCellValue(i, 2, str(round(r["Pesos"],2))) 
            
            if r["Tarjetas"] != None :
                tarjetas = Decimal(str(r["Tarjetas"])).quantize(Decimal("0.10"))
                self.grid1.SetCellValue(i, 3, str(round(r["Tarjetas"],2))) 
            
            if r["Total"] != None  :
                comision = Decimal(str((1 * r["Total"]) / 100)).quantize(Decimal("0.10"))
                ctacte = Decimal(str(total - pesos - tarjetas)).quantize(Decimal("0.10"))
                self.grid1.SetCellValue(i, 4, str(ctacte)) 
                self.grid1.SetCellValue(i, 5, str(comision))
                marca = True

            self.grid1.SetCellAlignment(i, 1, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(i, 2, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(i, 3, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(i, 4, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
            self.grid1.SetCellAlignment(i, 5, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)

            if marca:
                #si borra el "continue" debe borrar el incremento en 1 de i de la linea anterior al "continue"
                i = i + 1
                self.grid1.AppendRows()
                marca = False

##            continue
##            sells = sellManager.get_sells(r["idvendedora"], year, month)
##            points = ruleManager.calculate_points(sells, rules)
##            self.grid1.SetCellValue(i, 6, str(points))
##            
##            i = i + 1

        #self.grid1.SetCellValue(i, 4,   ) #
        total1 = Decimal("0.0")
        total2 = Decimal("0.0")
        total3 = Decimal("0.0")
        total = Decimal("0.0")
        self.grid1.AppendRows()
        for r in xrange(i):
            if self.grid1.GetCellValue(r,1) != "":
                total1 = total1 + Decimal(self.grid1.GetCellValue(r,1))
            if self.grid1.GetCellValue(r,2) != "":
                total2 = total2 + Decimal(self.grid1.GetCellValue(r,2))
            if self.grid1.GetCellValue(r,3) != "":
                total3 = total3 + Decimal(self.grid1.GetCellValue(r,3))
            if self.grid1.GetCellValue(r,4) != "":
                total = total + Decimal(self.grid1.GetCellValue(r,4))
        
        self.grid1.SetCellValue(i ,0,"TOTALES ")
        self.grid1.SetCellValue(i ,1,str(total1))
        self.grid1.SetCellValue(i ,2,str(total2))
        self.grid1.SetCellValue(i ,3,str(total3))
        self.grid1.SetCellValue(i ,4,str(total))

        self.grid1.SetCellAlignment(i, 1, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
        self.grid1.SetCellAlignment(i, 2, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
        self.grid1.SetCellAlignment(i, 3, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
        self.grid1.SetCellAlignment(i, 4, wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
